import React from "react";
import { useMessage } from "../hooks/MessageHook"; 

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
      error: null,
    };
  }

  static getDerivedStateFromError(error) {    
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {   
    try {
      const { showError } = this.props.messageContext;
      showError(error.message || "Something went wrong!", {
        duration: 8000, 
      });
      console.error("Caught error:", error, errorInfo); 
    } catch (e) {
      console.error("ErrorBoundary failed to show message:", e);
    }
  }

  render() {
    const { hasError, error } = this.state;
    const { fallback, children } = this.props;

    if (hasError && fallback) {    
      return typeof fallback === "function" ? fallback(error) : fallback;
    }   
    return children;
  }
}

const ErrorBoundaryWithContext = ({ fallback, children }) => {
  const messageContext = useMessage(); 
  return (
    <ErrorBoundary messageContext={messageContext} fallback={fallback}>
      {children}
    </ErrorBoundary>
  );
};

export default ErrorBoundaryWithContext;